<template>
    <div class="container">
      <div class="input-suffix" >
        <el-input placeholder="搜索活动"  v-model="input" >
          <template #suffix>
            <el-icon class="el-icon-search" style=" margin-right: 12px;"></el-icon>
          </template>
        </el-input>
      </div>  
    </div>

    <div class="container1" >
      <div class="condiction" style="margin-left: 80px; margin-top: 20px; width: 1500px; height: 30px;">
         <el-select size='middle' v-model="selection1" multiple collapse-tags placeholder="活动类型" style="width: 200px;" @input="updateFilter" > 
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
  
        <el-select size='middle' v-model="selection2" multiple collapse-tags placeholder="活动校区" style="width: 200px;  margin-left:50px;" @input="updateFilter" >
          <el-option
            v-for="item in options1"
            :key="item.value1"
            :label="item.label1"
            :value="item.value1">
          </el-option>
        </el-select>
  
        <el-select size='middle' v-model="selection3" multiple collapse-tags placeholder="活动状态" style="width: 200px;  margin-left:50px;" @input="updateFilter">
          <el-option
            v-for="item in options2"
            :key="item.value2"
            :label="item.label2"
            :value="item.value2">
          </el-option>
        </el-select>
      </div>      
    </div>
  
    <div class="container2">
      <div style="margin-left: 100px; margin-top: 15px; width: 1100px;">
        <el-row >
          <el-col :span="24" v-for="(activity,index) in displayedActivities" :key="index">
              <el-card class="card" shadow="hover" :body-style="{ padding: '0px' }" style="height: 200px;width: 1000px;margin-bottom: 30px; margin: 12px; padding: 12px;">
                  <el-row>
                      <el-col :span="4"><img :src="getTypeLogo(activity.Type)"  style="width: 50px; height:50px; margin-right: 32px; margin-top: 6px"></el-col>

                      <el-col :span="15">
                          <div style="margin-top: 7px;height: 50px; width: 660px;">
                              <p style="font-size: 24px; font-family: Arial;  float: left; font-weight: 600;  margin: 0 0 0px; text-align: left;
                              display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1; overflow: hidden;text-overflow: ellipsis;">{{activity.ATitle}}</p>
                          </div>
                      </el-col>

                      <el-col :span="3">
                          <el-tag style="font-size: 18px; padding: 14px 28px;margin-top: 10px">{{getStateText(activity.State)}}</el-tag>
                      </el-col>
                      
                      <el-col :span="1">
                          <div @click="toggleCollect(activity.Aid,index)" style="margin-left: 20px;;">
                            <el-icon v-if="collected[index] === 1" :style="'color: #f9d423; font-size: 32px; position: absolute; top: 8px; right: 15px;'">
                            <StarFilled />
                            </el-icon>
                            <el-icon v-else :style="'color:#CCD8FFFF; font-size: 27px; position: absolute; top: 12px; right: 16px;'">
                            <Star />
                            </el-icon>
                          </div>
                      </el-col>
                  </el-row>

                  <div style="margin-top:-12px; margin-left:165px; height: 10px;width: 800px;text-align: left">
                    <el-tag effect="dark" size='small' type="success" style="opacity: 0.7; font-size: 14px; padding:  8px 14px;">{{getCampusText(activity.Campus)}}</el-tag>
                    <el-tag effect="dark" size='small' type="warning" style="opacity: 0.7; margin-left: 10px;font-size: 14px; padding: 8px 14px;">{{getTypeText(activity.Type)}}</el-tag>
                    <el-tag v-if="getPermissionText(activity.Permission)" effect="dark" size="small" type="danger" 
                      style="opacity: 0.7; margin-left: 10px; font-size: 14px; padding: 8px 14px;">{{ getPermissionText(activity.Permission) }}
                    </el-tag>
                  </div>
      
                  <div style="text-align: left; margin-left:165px; margin-top:25px; font-family: Arial; font-size: 18px;width: 700px; height: 100px;">
                      <p style="font-size:16px; height:16px;"><strong><span style="font-size: 16px;">举办社团：</span></strong> {{clubNames[index]}}</p>
                      <p style="font-size: 16px; height:16px;"><strong><span style="font-size: 16px;">举办地点：</span></strong> {{activity.Place}}</p>
                      <p style="font-size: 16px; height:16px"><strong><span style="font-size: 16px;">报名时间：</span></strong> {{getFormatTime(activity.StartTime)}} - {{getFormatTime(activity.EndTime)}}</p>
                      <p style="font-size: 16px; height:16px"><strong><span style="font-size: 16px;">举办时间：</span></strong> {{getFormatTime(activity.Stime)}} - {{getFormatTime(activity.Etime)}}</p>
                  </div>

                  <div>
                      <el-button type="success" style="opacity: 0.95; margin-top: -50px; margin-left:720px; height:30px; width: 130px;font-size: 18px;" @click="showDialog(activity)">查看详情</el-button>
                      <el-dialog v-model="dialogVisible" width=800px :modal="false" :before-close="handleClose" >
                        <div style="text-align: left; margin-left:60px; margin-top: -40px; font-family: Arial; width:630px;">
                            <p style="font-size: 26px;font-weight: 600;">{{ currentActivity.ATitle }} </p>
                            <span style="font-size:20px;font-weight: 550;">活动内容：</span>
                            <p style="font-size: 18px;" v-html="formattedContent"> </p>
                            <span style="font-size: 20px;font-weight: 550;">报名要求：</span>
                            <p style="font-size: 18px;" v-html="formattedRequirement"></p>
                        </div>
                        <div style="margin-top: 40px; display: flex;  justify-content: center;">
                          <span>
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="joinActivity()">报名</el-button>
                          </span>
                        </div>
                      </el-dialog>
                      <div v-if="dialogVisible" class="overlay"></div>
                  </div>
                  
              </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <div>
      <el-backtop :right="80" :bottom="100" :visibility-height="700" style="width: 50px; height:50px;color: green; background-color: rgba(33, 107, 33, 0.2); line-height: 50px;" />
    </div>

    <div class="bottom-pagination">
      <el-button-group>
          <el-button type="primary" icon="el-icon-arrow-left" style="height: 35px;width:90px; font-size:18px; background-color: rgba(33, 107, 33, 0.7);"
          :disabled="currentPage <= 1" @click="goToPage(currentPage-1)">上一页</el-button>
          <el-button type="primary" style="margin-left: 120px;height: 35px;width:90px; font-size:18px; background-color: rgba(33, 107, 33, 0.7);"
          :disabled="currentPage >= totalPages()" @click="goToPage(currentPage+1)">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
      </el-button-group>
      <div style="margin-top: -28px; margin-left: 4px; font-size: 22px;">
          <span >{{ currentPage}} / {{totalPages()}}</span>
      </div>    
    </div>
  </template>
    
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {     
        input: '',
        selection1: [],
        selection2: [],
        selection3: [],
        currentPage: 1, 
        elementsPerPage:12,
        activities:[], 
        clubNames:[],
        showactivities:[],
        collected:[],
        dialogVisible:false,
        currentActivity: {},
        response: {},

        options: [{
          value: 1,
          label: '思想政治类'
        }, {
          value: 2,
          label: '学术科技类'
        }, {
          value: 3,
          label: '体育竞技类'
        }, {
          value: 4,
          label: '志愿公益类'
        }, {
          value: 5,
          label: '文化艺术类'
        }],

        options1: [{
          value1: 1,
          label1: '南校园'
        }, {
          value1: 2,
          label1: '北校园'
        }, {
          value1: 3,
          label1: '珠海校区'
        }, {
          value1: 4,
          label1: '深圳校区'
        }, {
          value1: 5,
          label1: '东校园'
        },{
          value1: 6,
          label1: '五校园'
        }], 

        options2: [{
          value2: 1,
          label2: '待报名'
        },{
          value2: 2,
          label2: '报名中'
        }, {
          value2: 3,
          label2: '待开展'
        }, {
          value2: 4,
          label2: '开展中'
        }, {
          value2: 5,
          label2: '已结束'
        }],
      }
    },
    
    methods:{
      totalPages() {
        return Math.ceil(this.showactivities.length / this.elementsPerPage);
      },
  
      currentpage(len){
        this.currentPage = len==0?0:1;
      },

      getFormatTime(time) {
        let date = new Date(time); 
        let year = date.getFullYear();
        let month = (date.getMonth() + 1).toString().padStart(2, '0'); 
        let day = date.getDate().toString().padStart(2, '0');
        let hours = date.getHours().toString().padStart(2, '0');
        let minutes = date.getMinutes().toString().padStart(2, '0');
        let seconds = date.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      
      toggleCollect(aid,index) {
        const collectedStatus = this.collected[index];
        this.sendCollectStatus(aid,collectedStatus);
        this.collected[index] = this.collected[index] === 1 ? 0 : 1;// 切换收藏状态   
      },
  
      sendCollectStatus(aid,collectedStatus) {     
        const formData = new FormData()
        formData.append('uid', this.$store.state.userinfo.account)
        formData.append('aid',aid)
        formData.append('collected',collectedStatus)
        // 使用axios或其他HTTP客户端库发送POST请求
        axios.post('/api/activity/CollectActivity', formData)
          .then(response => {
            console.log(response);
          })
          .catch(error => {
            console.error(error);
          });
      },

      goToPage(pageNumber) {
        if (pageNumber > 0 && pageNumber <= this.totalPages()) {
          this.currentPage = pageNumber;
        }
      },
  
      updateFilter() {
      },

      showDialog(activity) {
        this.dialogVisible = true;
        this.currentActivity = activity; 
      },

      handleClose(done) {
        done();
      },

      getCurrentDateTime() {
          const now = new Date();
          const year = now.getFullYear();
          const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1，并且保证两位数
          const day = String(now.getDate()).padStart(2, '0');
          const hours = String(now.getHours()).padStart(2, '0');
          const minutes = String(now.getMinutes()).padStart(2, '0');
          const seconds = String(now.getSeconds()).padStart(2, '0');

          const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
          
          return formattedDateTime;
      },

      joinActivity(){
        const formData = new FormData()
        formData.append('uid', this.$store.state.userinfo.account)
        formData.append('aid', this.currentActivity.Aid)
        formData.append('time', this.getCurrentDateTime())

        axios.post('/api/joinActivity', formData)
          .then(response => {
            this.response = response.data.data.permission;

            switch (this.response) {
              case 0:
                this.showMessageBox('报名成功', 'success');
                break;
              case 1:
                this.showMessageBox('您已报名参加，请耐心等待结果', 'info');
                break;
              case 2:
                this.showMessageBox('您已报名成功，无需再报名', 'success');
                break;
              case 3:
                this.showMessageBox('该活动仅限本社团成员参加', 'warning');
                break;
              default:
                this.showMessageBox('未知响应', 'error');
            }
            })
          .catch(error => {
            console.error('Error joining activity:', error);
          });
      },

      showMessageBox(message, type) {
        this.$alert(message, '提示', {
          confirmButtonText: '确定',
          type: type,
        });
      },
    },
  
    computed: {
      getStateText() {
        return (state) => {
          switch (state) {
            case 1:
                return '待报名';
            case 2:
                return '报名中';
            case 3:
                return '待开展';
            case 4:
                return '开展中';
            case 5:
                return '已结束';
            default:
                return '其它';
          }
        };
      },

      getTypeText() {
        return (type) => {
          switch (type) {
            case 1:
                return '思想政治类';
            case 2:
                return '学术科技类';
            case 3:
                return '体育竞技类';
            case 4:
                return '志愿公益类';
            case 5:
                return '文化艺术类';
            default:
                return '';
          }
        };
      },
  
      getCampusText() {
        return (Campus) => {
          switch (Campus) {
            case 1:
                return '南校区';
            case 2:
                return '北校区';
            case 3:
                return '珠海校区';
            case 4:
                return '深圳校区';
            case 5:
                return '东校区';
            case 6:
                return '五校园'
            default:
                return '';
          }
        };
      },

      getPermissionText() {
        return (permission) => {
          switch (permission) {
            case 1:
                return '仅本社团成员可报名';
            default:
                return '';
          }
        };
      },
  
      getTypeLogo() {
        return (type) => {
          switch (type) {
            case 1:
                return require('../assets/1.jpg');
            case 2:
                return require('../assets/2.jpg');
            case 3:
                return require('../assets/3.jpg');
            case 4:
                return require('../assets/4.jpg');
            case 5:
                return require('../assets/5.jpg');
            default:
                return '';
          }
        };
      },

      displayedActivities() {
        const startIndex = (this.currentPage - 1) * this.elementsPerPage;
        const endIndex = startIndex + this.elementsPerPage;
        return this.showactivities.slice(startIndex, endIndex);
      },
   
      filteredactivities() {
        const filteredactivities = this.activities.filter(activity => {
          const TypeMatch = this.selection1.length === 0 || this.selection1.includes(activity.Type);
          const campusMatch = this.selection2.length === 0 || this.selection2.includes(activity.Campus);
          const statusMatch =  this.selection3.length === 0 || this.selection3.includes(activity.State);
          const inputMatch = this.input ? activity.Aline.includes(this.input) : true;
          return inputMatch&&TypeMatch && campusMatch && statusMatch;
        });
        this.currentpage(filteredactivities.length)
        return filteredactivities;
      },
      formattedContent() {
        return this.currentActivity.Content.replace(/\r\n|\n/g, '<br>');
      },
      formattedRequirement() {
        return this.currentActivity.Requirement.replace(/\r\n|\n/g, '<br>');
      }
    },
  
    watch: {
      filteredactivities(newVal) {
        this.showactivities = newVal; 
      },
      
    },
  
    mounted() {
      const params = new URLSearchParams();
      params.append('uid', this.$store.state.userinfo.account);
  
      axios.get('http://localhost:8080/api/activity', { params })
        .then(response => {
          this.activities = response.data.data.activities;
          this.clubNames =response.data.data.clubNames;
          this.showactivities =response.data.data.activities;
          this.collected = response.data.data.collected;
        })
        .catch(error => {
          console.error('Error fetching activities:', error);
        });
    }
  };
  </script>
    
  <style>
  .container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: -50px;
  }
  
  .container1 {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .container2{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .input-suffix {
    display: flex;
    justify-content: center;
    margin-top: 50px;
    width: 280px;
    height: 30px;
  }
  
  .input-suffix .el-input input {
    font-size: 16px; 
    font-family: Arial; 
    margin-left: 10px;
  }

  .card:hover {
    border-color: #69b569; /* 设置卡片边框为绿色 */
    background-color: rgba(33, 107, 33, 0.12); /* 浅绿色背景，可以根据需要调整颜色代码 */
  }
  
  .bottom-pagination {
    position: relative;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
    bottom: 0;
    margin-left:20px;
    height:80px;
  }

  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #5a58581a;
    z-index: 999;
  }

  .el-dialog {
    box-shadow: none !important;
  }
</style>